package com.xzjt.web.controller;

import cn.hutool.json.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.xzjt.common.components.RedisService;
import com.xzjt.common.utils.MD5Utils;
import com.xzjt.common.utils.PasswordUtils;
import com.xzjt.common.utils.R;
import com.xzjt.web.annotation.SysLogAnnotation;
import com.xzjt.web.entity.SysRole;
import com.xzjt.web.entity.SysUser;
import com.xzjt.web.config.JwtService;
import com.xzjt.web.service.SysRoleService;
import com.xzjt.web.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName: SysUserController
 * @Author: yuandong
 * @Date 2021/10/11 13:13
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private JwtService jwtService;

    @Autowired
    private RedisService redisService;


    /**
     * 分页查询
     * 如果前端没有传递参数，可以在这里使用defaultValue设置默认值
     *
     * @param pageNum
     * @param pageSize
     * @param sysUser
     * @return
     */
    @SysLogAnnotation("查询用户列表")
    @GetMapping("/selectList")
    public R<?> selectList(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize, SysUser sysUser) {

        PageHelper.startPage(pageNum, pageSize);

        List<SysUser> userList = sysUserService.selectUserList(sysUser);
        PageInfo<SysUser> pageInfo = new PageInfo<>(userList);

        return R.ok(pageInfo);
    }


    /**
     * 查询用户详情
     *
     * @param token
     * @return
     */
    @SysLogAnnotation("用户详情")
    @GetMapping("/info")
    public R userinfo(@RequestHeader String token) {
        String username = jwtService.getUsername(token);
        SysUser sysUser = sysUserService.selectByUsername(username);
        //获取用户对应的角色
        List<SysRole> roleList = roleService.selectRoleAll();

        //如果是超管则查询所有角色
        List<SysRole> roles = sysUser.getIsAdmin() == 1 ? roleList : roleList.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList());

        JSONObject ret = new JSONObject();
        ret.put("roles", roles);
        ret.put("user", sysUser);

        return R.ok(ret);
    }


    /**
     * 新增用户
     *
     * @return
     * @RequestBody 前台传递的json 转换成user对象
     */
    @SysLogAnnotation("新增用户")
    @PostMapping("/save")
    public R<?> save(@RequestBody SysUser user) {

        //验证用户名是否唯一
        int count = this.sysUserService.checkUserNameUnique(user.getUsername());
        if (count > 0) {
            return R.error("-1", "失败，登录账号已存在");
        }


        if (user.getPassword() == null || user.getPassword().equals("")) {
            user.setPassword("123456");
        }

        String pwd= MD5Utils.md5(user.getPassword());
        //String salt = PasswordUtils.generateSalt();
        String salt = user.getUsername();

        user.setSalt(salt);
        user.setPassword(PasswordUtils.encodePassword(pwd, salt));

        int flag = this.sysUserService.save(user);
        if (flag > 0) {
            return R.ok();
        } else {
            return R.error("-1", "新增用户失败");
        }

    }


    /**
     * 修改用户
     *
     * @param user
     * @return
     */
    @RequiresRoles(value = {"admin"}, logical = Logical.OR)
    @SysLogAnnotation("修改用户")
    @PostMapping("/update")
    public R<?> update(@RequestBody SysUser user) {
        this.sysUserService.updateUserById(user);
        return R.ok();
    }


    /**
     * 删除用户
     *
     * @param userId
     * @return
     */
    @RequiresRoles(value = {"admin"}, logical = Logical.OR)
    @DeleteMapping("/del/{id}")
    public R del(@PathVariable("id") Integer userId) {

        this.sysUserService.delUser(userId);
        return R.ok();
    }


    /**
     * 用户重置密码
     *
     * @return
     */
    @GetMapping("/resetPassword/{id}")
    public R resetPassword(@PathVariable("id") Integer userId) {
        int flag = this.sysUserService.resetPassword(userId);
        if (flag > 0) {
            return R.ok();
        }
        return R.error("-1", "密码重置失败");

    }


}
